package com.xsqf.jt808.netty.handler;

import com.xsqf.jt808.common.config.ChannelManager;
import com.xsqf.jt808.common.vo.req.terminal.HeartBeatMsg;
import com.xsqf.jt808.common.vo.resp.CommonResp;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author:
 * @Date: 2020-5-14
 * @Description: 心跳消息->CommonResp
 * @Version: 1.0
 */

@Slf4j
@Component
@ChannelHandler.Sharable
public class HeartBeatMsgHandler extends BaseHandler<HeartBeatMsg> {
    @Autowired
    private ChannelManager channelManager;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HeartBeatMsg msg) throws Exception {
        log.info("心跳："+msg.toString());
        CommonResp resp = heartBeat(msg, getSerialNumber(ctx.channel()));
        if (resp != null) {
            write(ctx, resp);
        } else {
            ctx.close(channelManager.get(msg.getHeader().getTerminalPhone()).newPromise());
        }

    }

    public CommonResp heartBeat(HeartBeatMsg msg, short flowId) {
        CommonResp resp = new CommonResp();
        resp.getHeader().setTerminalPhone(msg.getHeader().getTerminalPhone());
        resp.getHeader().setFlowId(flowId);
        resp.setReplyFlowId(msg.getHeader().getFlowId());
        resp.setReplyId(msg.getHeader().getMsgId());
        resp.setResult(CommonResp.FAILURE);

        //验证session信息
        Object isAuthenticated = redisTemplate.opsForHash()
                .get("KEY:" + msg.getHeader().getTerminalPhone(), "isAuthenticated");
        if (isAuthenticated != null) {
            resp.setResult(CommonResp.SUCCESS);
            return resp;
        }
        return null;
    }
}
